<?php

/**
 * File manipulation utilities that simplify a few common file operations.
 * 
 * @author Michael Krotscheck
 */
class Core_Util_File {
	/**
	 * This method tries to delete a file.
	 *
	 * @param string $path
	 */
	static public function deleteFile($path) {
		if (!file_exists($path)) {
			return true;
		}

		if (!is_file(($path))) {
			throw new Exception("This is not a file: {$path}");
		}

		if (Core_Util_File::setPermissions($path, 0777)) {
			unlink($path);
			return true;
		} else {
			throw new Exception("Invalid permissions on: {$path}");
			return false;
		}
	}

	/**
	 * Recursively delete a folder and all the files in it.\
	 *
	 * @param string $path
	 * @throws Exception
	 */
	static public function deleteFolder($path) {
		if (!file_exists($path)) {
			return true;
		}

		if (!is_dir($path)) {
			throw new Exception("This is not a folder: {$path}");
		}

		// Enumerate all the files and delete them.
		$dir = opendir($path);

		while ($file = readdir($dir)) {
			if ($file != '.' && $file != '..') {
				$childPath = $path."/".$file;
				if (is_dir($childPath)) {
					Core_Util_File::deleteFolder($childPath);
				} else {
					Core_Util_File::deleteFile($childPath);
				}
			}
		}

		closedir($dir);

		// Delete the directory
		if (Core_Util_File::setPermissions($path, 0777)) {
			rmdir($path);
			return true;
		} else {
			throw new Exception("Invalid permissions on: {$path}");
			return false;
		}
	}

	/**
	 * Set the permissions on a given file path.
	 *
	 * @param string $path
	 * @param string $perms
	 */
	static public function setPermissions($path, $perms) {
		try {
			chmod($path, $perms);
			return true;
		} catch (Exception $e) {
			return false;
		}
	}

}
